package com.class06.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
@WebListener("/servletB")
public class MySessionListener implements HttpSessionListener, HttpSessionAttributeListener {
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session创建了");
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session销毁了");
    }

    public void attributeAdded(HttpSessionBindingEvent event) {
//        获取session对象
        HttpSession session = event.getSession();
//        获取session的id
        System.out.println(session.getId());
//        获取session的创建时间
        long creationTime = session.getCreationTime();
//        格式化时间
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(creationTime);
        System.out.println("session创建时间为：" + format);
//        获取添加的属性名和值
        String name = event.getName();
        Object value = event.getValue();
        System.out.println("session中添加了"+name+"--"+value);


    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("session中移除了一个属性");
        System.out.println(event.getName()+"--"+event.getValue());
//        invalidate() 让session立即失效
        event.getSession().invalidate();
    }

    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        System.out.println("session中替换了一个属性");
        System.out.println(event.getName()+"获取出来的旧值为："+event.getValue()
        + "，新值为："+session.getAttribute(event.getName())
        );

    }

}
